package common

import (
	"bytes"
	"os"
	"unsafe"
)

type Buffer struct {
	buffer bytes.Buffer
}

func (this *Buffer) WriteByte(val byte) {
	this.buffer.WriteByte(val)
}

func (this *Buffer) WriteString(val string) {
	if len(val) <= 0 {
		this.WriteInt64(0)
	} else {
		this.WriteInt64((int64)(len(val) + 1))
		this.WriteBytes([]byte(val))
		this.WriteByte(0)
	}
}

func (this *Buffer) WriteBytes(val []byte) {
	this.buffer.Write(val)
}

func (this *Buffer) WriteInt32(val int32) {
	this.WriteData((uintptr)(unsafe.Pointer(&val)), 4)
}

func (this *Buffer) WriteInt64(val int64) {
	this.WriteData((uintptr)(unsafe.Pointer(&val)), 8)
}

func (this *Buffer) WriteFloat64(val float64) {
	this.WriteData((uintptr)(unsafe.Pointer(&val)), 8)
}

func (this *Buffer) WriteData(addr uintptr, size uint) {
	for range size {
		this.WriteByte(*(*byte)(unsafe.Pointer(addr)))
		addr += 1
	}
}

func (this *Buffer) WriteInt32Array(vals []int32) {
	this.WriteInt32(int32(len(vals)))
	for _, val := range vals {
		this.WriteInt32(val)
	}
}

func (this *Buffer) WriteToFile(fileName string) error {
	return os.WriteFile(fileName, this.buffer.Bytes(), 0644)
}

func NewBuffer() *Buffer {
	return &Buffer{}
}
